package com.centanet.framework.network;

import android.support.v4.util.ArrayMap;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RetryPolicy;
import com.centanet.framework.interfaces.IRequestEncode;
import com.centanet.framework.interfaces.IResponseListener;

/**
 * api
 */
public abstract class AbstractFrameApi<T> implements IRequestEncode {

    private final Class<?> tag;
    private final Class<T> aClass;
    private final IResponseListener<T> iResponseListener;

    /**
     * @param tag               请求标签：Activity.class、Fragment.class、Service.class等等；
     * @param aClass            Gson解析目标实体；
     * @param iResponseListener 响应监听；
     */
    public AbstractFrameApi(Class<?> tag, Class<T> aClass, IResponseListener<T> iResponseListener) {
        this.tag = tag;
        this.aClass = aClass;
        this.iResponseListener = iResponseListener;
    }

    /**
     * 公共ip
     */
    protected abstract String getIp();

    /**
     * 方法
     */
    protected abstract String getPath();

    /**
     * 请求方式
     */
    protected int getMethod() {
        return Request.Method.GET;
    }

    /**
     * 请求header
     */
    protected abstract ArrayMap<String, String> getHeaders();

    /**
     * {@link DefaultRetryPolicy},{@link RetryPolicy}
     */
    protected RetryPolicy getRetryPolicy() {
        return new DefaultRetryPolicy();
    }

    /**
     * the content type of the POST or PUT body.
     */
    protected String getBodyContentType() {
        return "application/x-www-form-urlencoded; charset=UTF-8";
    }

    /**
     * 是否使用缓存
     */
    protected boolean getShouldCache() {
        return false;
    }

    /**
     * 编码 默认UTF-8
     *
     * @return 编码
     */
    protected String getParamsEncoding() {
        return "UTF-8";
    }

    /**
     * 开始请求
     */
    public void startRequest() {
        VolleyRequestQueue.getRequestQueue().add(new GsonRequest.Builder<>(aClass, iResponseListener)
                .url(url().toString())
                .method(getMethod())
                .headers(getHeaders())
                .params(params())
                .tag(tag)
                .retryPolicy(getRetryPolicy())
                .bodyContentType(getBodyContentType())
                .shouldCache(getShouldCache())
                .build());
    }
}
